#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "./sps_pps_analyze.h"
#include "./sps_analyze_lib2.h"

#define SPS_DATA_SIZE  (25)

// 0x00,0x00,0x00,0x01
//    0x67
// 0110 0111
//    0x64   |    0x00   |    0x33   |    0xac
// 0110 0100 | 0000 0000 | 0011 0011 | 1010 1100

//    0x15   |    0x14   |    0xa0   |    0x50
// 0001 0101 | 0001 0100 | 1010 0000 | 0101 0000

//    0x05   |    0xba   |    0x68   |    0x80
// 0000 0101 | 1011 1010 | 0110 1000 | 1000 0000

//    0x00   |    0x01   |    0xf4   |    0x00
// 0000 0000 | 0000 0001 | 1111 0100 | 0000 0000

//    0x00   |    0x75   |    0x30   |    0x02
// 0000 0000 | 0111 0101 | 0011 0000 | 0000 0010
uint8_t data_buffer[SPS_DATA_SIZE] = {0x00,0x00,0x00,0x01,0x67,0x64,0x00,0x33,0xac,0x15,0x14,0xa0,0x50,0x05,0xba,0x68,0x80,0x00,0x01,0xf4,0x00,0x00,0x75,0x30,0x02 };
SPS sps_info = {0};
get_bit_context sps_data = {0};

int data_write(char *filename, uint8_t *data_buf, uint8_t buf_size)
{
    FILE *file = fopen(filename, "w+");
    if (file == NULL) 
    {
        perror("无法打开文件!!!");
        return EXIT_FAILURE;
    }

    // 使用fwrite写入二进制数据
    size_t written = fwrite(data_buf, 1, buf_size, file);
    if (written != buf_size) 
    {
        perror("写入文件时出错!!!");
        fclose(file);
        return EXIT_FAILURE;
    }

    // 关闭文件
    fclose(file);
    printf("数组数据已成功写入文件。\n");

    return 0;
}

int main(int argc, const char *argv[])
{
    int ret = 0;
    int width = 0;
    int height = 0;
    /* code */ 
    // sps 数据初始化，只需要初始化这两个成员即可
    sps_data.buf = data_buffer + 5;
    sps_data.buf_size = sizeof(data_buffer)/sizeof(data_buffer[0]) - 5;

    // 解析sps信息
    ret = h264dec_seq_parameter_set((void *)&sps_data, &sps_info);
    if(ret < 0)
    {
        printf("error h264dec_seq_parameter_set fail!ret=%d\n", ret);
        return -1;
    }

    width = h264_get_width(&sps_info);
    height = h264_get_height(&sps_info);

    printf("sps info width=%d height=%d\n", width, height);

    // 将数据写入文件，方便使用 H264BSAnalyzer.exe 解析查看
    //data_write("sps_data.h264", data_buffer, SPS_DATA_SIZE);

    sps_analyze_lib2_demo(argc, argv);

    return 0;
}